package com.ziytek.web.citizen.service.impl;

import com.google.gson.Gson;
import com.ziytek.web.citizen.constant.NumConstant;
import com.ziytek.web.citizen.constant.ServerConstant;
import com.ziytek.web.citizen.mapper.BasicStepSettingsMapper;
import com.ziytek.web.citizen.model.bean.AllComprehensiveDetails;
import com.ziytek.web.citizen.model.bean.BatteriesComprehensiveDetails;
import com.ziytek.web.citizen.model.req.BatteryListQueryReq;
import com.ziytek.web.citizen.model.rsp.BatteryComprehensiveRsp;
import com.ziytek.web.citizen.service.itf.BatteryComprehensiveService;
import com.ziytek.web.citizen.util.CabinetNoUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fenghx
 * @version v1.0
 * @className QueryBatteryDetailsServiceImp
 * @description 功能描述
 * @date 2023/8/7 13:25
 **/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class BatteryComprehensiveServiceImpl implements BatteryComprehensiveService {
    private final Gson gson;
    private final BasicStepSettingsMapper basicStepSettingsMapper;
    private final CompletableFutureServiceImpl completableFutureService;

    private BatteryComprehensiveRsp check(BatteryListQueryReq request) {
        BatteryComprehensiveRsp response = new BatteryComprehensiveRsp();
        response.success();
        if (request == null) {
            response.error("batteryComprehensiveListQuery failed request is empty.");
            log.error("batteryComprehensiveListQuery failed request is empty.");
            return response;
        }

        if (!request.requestCheck()) {
            response.error("接口请求参数检验失败");
            return response;
        }

        String error = request.requestCheckAndResult();
        if (StringUtils.isNotBlank(error)) {
            response.error(error);
            return response;
        }

//        if (GlobalConfig.isStepSwitching()) {
//            log.info("batteryDetailsQuery数据库变更进行中，接受数据不处理");
//            return response;
//        }

        return response;
    }

    @Override
    public BatteryComprehensiveRsp batteryComprehensiveListQuery(BatteryListQueryReq request) {
        BatteryComprehensiveRsp response = check(request);
        if (!ServerConstant.SUCCESS.equalsIgnoreCase(response.getRetCode())) {
            return response;
        }

        String cabinetNo = CabinetNoUtil.getCabinetNo(request.getCabinetNo());
//        LinkedHashMap<String, List<StageComprehensiveTable>> stageDataMap = getStageDataMapList(request);
//        if (CollectionUtils.isEmpty(stageDataMap)) {
//            return response;
//        }

       // getBatteryComprehensiveRsp(response, completableFutureService.comprehensiveProcessData(stageDataMap, cabinetNo));
        //getBatteryComprehensiveRsp(response, completableFutureService.comprehensiveProcessData(null, cabinetNo));
        return response;
    }

    private void getBatteryComprehensiveRsp(BatteryComprehensiveRsp response, LinkedHashMap<String, List<BatteriesComprehensiveDetails>> map) {
        List<AllComprehensiveDetails> allComprehensiveDetails = new ArrayList<>();
        for (Map.Entry<String, List<BatteriesComprehensiveDetails>> entry : map.entrySet()) {
            AllComprehensiveDetails all = new AllComprehensiveDetails();
            all.setType(entry.getKey());
            all.setData(entry.getValue());
            allComprehensiveDetails.add(all);
        }

        response.setData(allComprehensiveDetails);
    }


//    public LinkedHashMap<String, List<StageComprehensiveTable>> getStageDataMapList(BatteryListQueryReq request) {
//        if (request == null) {
//            return null;
//        }
//        String cabinetNo = CabinetNoUtil.getCabinetNo(request.getCabinetNo());
//        //IssuedHistorySetting issuedHistorySetting = issuedHistorySettingMapper.findFirstByCabinetNoOrderByCreateTimeDesc(cabinetNo);
//        //if (issuedHistorySetting == null) {
//           // return null;
//        //}
//
//       // Long stepId = issuedHistorySetting.getStepId();
//        long stepId = 0L;
//        BasicStepSettings basicStepSettings = basicStepSettingsMapper.findFirstById(stepId);
//        if (basicStepSettings == null) {
//            return null;
//        }
//        List<AddSettings> settings = gson.fromJson(basicStepSettings.getStepSettings(), new TypeToken<List<AddSettings>>() {
//        }.getType());
//        if (CollectionUtils.isEmpty(settings)) {
//            return null;
//        } else {
//            settings.sort(Comparator.comparing(AddSettings::getSettingOrder));
//        }
//
//        LinkedList<String> typeLinkedList = new LinkedList<>();
//        for (AddSettings setting : settings) {
//            typeLinkedList.add(setting.getSetType());
//        }
//
//        //long startTime = issuedHistorySetting.getCreateTime();
//        long startTime = 0L;
//        List<StageComprehensiveTable> stageComprehensiveTables = stageComprehensiveMapper.queryComprehensiveListByCabinetNo(cabinetNo, startTime);
//        if (CollectionUtils.isEmpty(stageComprehensiveTables)) {
//            return null;
//        }
//
//        Map<String, List<StageComprehensiveTable>> map = stageComprehensiveTables.stream().collect(Collectors.groupingBy(StageComprehensiveTable::getSetType));
//        List<String> keyList = new ArrayList<>();
//        if (request.isPositionNormal()) {
//            String tier = ServerConstant.SIDE_B.equalsIgnoreCase(request.getSide()) ? String.valueOf(NumberUtils.toInt(request.getTier()) + NumConstant.INT_EIGHT) : request.getTier();
//            String position = ServerConstant.DOOR_R.equalsIgnoreCase(request.getDoor()) ? String.valueOf(NumberUtils.toInt(request.getPosition()) + NumConstant.INT_TEN_SIX) : request.getPosition();
//            String key = cabinetNo + ServerConstant.DATA_SEPARATOR + tier + ServerConstant.DATA_SEPARATOR + position;
//            keyList.add(key);
//        }
//
//        if (CollectionUtils.isEmpty(keyList) && request.isTierNormal()) {
//            keyList = getTierQueryKeys(cabinetNo, request.getSide(), request.getDoor(), request.getTier());
//        }
//        if (CollectionUtils.isEmpty(keyList) && request.isDoorNormal()) {
//            keyList = getDoorQueryKeys(cabinetNo, request.getSide(), request.getDoor());
//        }
//        if (CollectionUtils.isEmpty(keyList) && request.isSideNormal()) {
//            keyList = getSideKeys(cabinetNo, request.getSide());
//        }
//
//        if (CollectionUtils.isEmpty(keyList) && !request.isSideNormal()) {
//            keyList = getAllKeys(cabinetNo);
//        }
//
//        if (CollectionUtils.isEmpty(keyList)) {
//            return null;
//        }
//
//        LinkedHashMap<String, List<StageComprehensiveTable>> resultMap = new LinkedHashMap<>();
//        for (String setType : typeLinkedList) {
//            List<StageComprehensiveTable> list = map.get(setType);
//            if (CollectionUtils.isEmpty(list)) {
//                continue;
//            }
//            List<String> finalKeyList = keyList;
//            list = list.stream().filter(t -> t.getSetType().equalsIgnoreCase(setType) && finalKeyList.contains(t.getKey())).collect(Collectors.toList());
//            if (!CollectionUtils.isEmpty(list)) {
//                resultMap.put(setType, list);
//            }
//        }
//
//        return resultMap;
//    }
//

    /**
     * @return List<String> 16个数据
     */
    private List<String> getTierQueryKeys(String cabinetNo, String side, String door, String tier) {
        List<String> keyList = new ArrayList<>();

        if (ServerConstant.SIDE_A.equalsIgnoreCase(side)) {
            if (ServerConstant.DOOR_L.equalsIgnoreCase(door)) {
                for (int position = NumConstant.INT_ONE; position <= NumConstant.INT_TEN_SIX; position++) {
                    String key = cabinetNo + ServerConstant.DATA_SEPARATOR + tier + ServerConstant.DATA_SEPARATOR + position;
                    keyList.add(key);
                }
            }

            if (ServerConstant.DOOR_R.equalsIgnoreCase(door)) {
                tier = String.valueOf(NumberUtils.toInt(tier) + NumConstant.INT_EIGHT);
                for (int position = NumConstant.INT_ONE; position <= NumConstant.INT_TEN_SIX; position++) {
                    String key = cabinetNo + ServerConstant.DATA_SEPARATOR + tier + ServerConstant.DATA_SEPARATOR + position;
                    keyList.add(key);
                }
            }
        }
        if (ServerConstant.SIDE_B.equalsIgnoreCase(side)) {
            if (ServerConstant.DOOR_L.equalsIgnoreCase(door)) {
                for (int position = NumConstant.INT_TEN_SIX + 1; position <= NumConstant.INT_THIRTY_TWO; position++) {
                    String key = cabinetNo + ServerConstant.DATA_SEPARATOR + tier + ServerConstant.DATA_SEPARATOR + position;
                    keyList.add(key);
                }
            }

            if (ServerConstant.DOOR_R.equalsIgnoreCase(door)) {
                tier = String.valueOf(NumberUtils.toInt(tier) + NumConstant.INT_EIGHT);
                for (int position = NumConstant.INT_TEN_SIX + 1; position <= NumConstant.INT_THIRTY_TWO; position++) {
                    String key = cabinetNo + ServerConstant.DATA_SEPARATOR + tier + ServerConstant.DATA_SEPARATOR + position;
                    keyList.add(key);
                }
            }
        }
        return keyList;
    }

    private List<String> getDoorQueryKeys(String cabinetNo, String side, String door) {
        List<String> keyList = new ArrayList<>();
        for (int tier = NumConstant.INT_ONE; tier <= NumConstant.INT_EIGHT; tier++) {
            keyList.addAll(getTierQueryKeys(cabinetNo, side, door, String.valueOf(tier)));
        }
        return keyList;
    }

    private List<String> getSideKeys(String cabinetNo, String side) {
        List<String> keyList = new ArrayList<>();

        keyList.addAll(getDoorQueryKeys(cabinetNo, side, ServerConstant.DOOR_L));
        keyList.addAll(getDoorQueryKeys(cabinetNo, side, ServerConstant.DOOR_R));


        return keyList;
    }

    private List<String> getAllKeys(String cabinetNo) {
        List<String> keyList = new ArrayList<>();

        keyList.addAll(getSideKeys(cabinetNo, ServerConstant.SIDE_A));
        keyList.addAll(getSideKeys(cabinetNo, ServerConstant.SIDE_B));


        return keyList;
    }
}
